package stu.khy.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import stu.khy.dao.LeaveDao;
import stu.khy.entity.Employee;
import stu.khy.entity.Leave;
import stu.khy.util.PaginationSupport;




public abstract class BaseLeaveServiceImpl implements LeaveService {
	private LeaveDao leaveDao;

	@Override
	public void saveLeave(Leave leave) {
	}
	
	@Override
	public void checkLeave(Leave leave) {
	}

	@Override
	public PaginationSupport<Leave> getClaimVoucherPage(Employee emp,
			Leave leave, Date startDate, Date endDate, Integer pageNo,
			Integer pageSize) {
		PaginationSupport<Leave> result = new PaginationSupport<Leave>();

		if (pageNo > 0)
			result.setCurrPageNo(pageNo);
		if (pageSize > 0)
			result.setPageSize(pageSize);

		// 可以使用连接查询，配合投影，需要重新定义数据传输对象
		StringBuilder hqlBuilder = new StringBuilder("");
		List<Object> values = new ArrayList<>();
		this.buildBaseHql(emp, leave, startDate, endDate, hqlBuilder, values);

		int count = leaveDao.getTotalCount(hqlBuilder.toString(),
				values.toArray()).intValue();
		result.setTotalCount(count);

		if (count > 0) {
			// count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1
			int pageCount = (count + result.getPageSize() - 1)
					/ result.getPageSize();
			result.setTotalPageCount(pageCount);
			if (result.getCurrPageNo() > pageCount)
				result.setCurrPageNo(pageCount);

			this.addOrders(leave, hqlBuilder);

			List<Leave> items = leaveDao.findForPage(
					hqlBuilder.toString(), result.getCurrPageNo(),
					result.getPageSize(), values.toArray());
			result.setItems(items);
		}

		return result;
	}

	protected abstract void buildBaseHql(Employee emp, Leave leave,
			Date startDate, Date endDate, StringBuilder hqlBuilder,
			List<Object> values);

	protected abstract void addOrders(Leave leave, StringBuilder hqlBuilder);

	@Override
	public Leave findLeaveById(Long id) {
		return leaveDao.get(id);
	}
	
	public LeaveDao getLeaveDao() {
		return leaveDao;
	}

	public void setLeaveDao(LeaveDao leaveDao) {
		this.leaveDao = leaveDao;
	}

}
